<?php

namespace app\api\controller\attachment;


use app\api\controller\Api;
use app\common\config\logic\ConfigSystem;
use app\common\system\validate\AttachmentValidate;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Filesystem;
use util\Format;

class Attachment extends Api
{
    public function index()
    {
        $post = $this->request->post();
        $model = new \app\common\system\model\Attachment();

        list($cfg) = Format::pagination($post);
        $pg = $model->order('id desc')->paginate($cfg);
        $rows = $pg->getCollection();
        foreach ($rows as $row) {
            $row->append(['url']);
        }

        // 返回接口数据
        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);
        return success($result, '获取数据成功');
    }

    // 上传、分类信息
    public function upload()
    {
        $post = $this->request->post();
        // if (empty($post['pid'])) return error([], "请选择要上传的分类");
        $dir = !empty($post['field']) ? $post['field'] : 'file';
        // 获取上传配置
        $systemConfigLogic = new ConfigSystem();
        $uploadConfig = $systemConfigLogic->getConfigItem("upload");

        $file = $this->request->file('file');
        if (empty($file)) return error([], '请选择要上传的文件');


        $rules = [
            "file" => ["fileSize:{$uploadConfig['size']}", "fileExt:{$uploadConfig['ext']}"],
        ];
        $messages = [
            "file.fileSize" => '文件不超过',
            "file.fileExt" => '不支持的文件格式'
        ];
        $validateLogic = validate($rules, $messages);
        $checkRs = $validateLogic->check(['file' => $file]);
        if (!$checkRs) {
            return error([], $validateLogic->getError());
        }

        // 上传到本地服务器
        $saveName = \think\facade\Filesystem::disk("public")->putFile($dir, $file);
        if ($saveName) {
            $config = config('filesystem.disks');
            $saveName = $config['public']['url'] . '/' . str_ireplace('\\', '/', $saveName);
            $result['path'] = $this->request->domain() . $saveName;

            $data = [];
            $data['title'] = $file->getOriginalName();
            $data['att_dir'] = $saveName;
            $data['satt_dir'] = $saveName;
            $data['att_size'] = $file->getSize();
            $data['att_type'] = $file->getMime();
            $data['pid'] = $post['pid'];
            $data['image_type'] = 1;
            $data['module_type'] = $post['module_type'];
            $data['real_name'] = $file->getOriginalName();
            $model = new \app\common\system\model\Attachment();
            $model->save($data);
            return success($result, '上传成功');
        } else {
            return error([], '上传失败');
        }

    }

    // 创建信息
    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);

        // 验证提交的数据
        $validate = new AttachmentValidate();
        if (!$validate->scene('create')->check($post)) return error([], $validate->getError());

        $model = new \app\common\system\model\Attachment();
        try {
            $model->save($post);
            return success([], '添加成功');
        } catch (DbException $e) {
            return error([], '添加失败');
        }
    }

    // 编辑信息
    public function save()
    {
        $post = $this->request->post();
        // 验证提交的数据
        $validate = new AttachmentValidate();
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());

        $model = new \app\common\system\model\Attachment();
        $row = $model->where('id', $post['id'])->find();

        try {
            $row->save($post);
            return success([], '编辑成功');

        } catch (DbException $e) {

            return error([], $e->getMessage());
        }
    }

    // 删除
    public function delete()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');
        // 获取当前删除的编号
        $model = new \app\common\system\model\Attachment();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '该数据已不存在');

        // 获取当前的子
        try {
            $row->delete();
            return success([], '删除成功');
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }
    }
}